承诺问题 Node.js
issue with promise Node.js
我想弄清楚这个问题已经有一段时间了,但它太令人困惑了,所以我想问一下。
var listenKey = "";
const createListenKey = async () => {
await axios({
url: "/api/v3/userDataStream",
method: "POST",
baseURL: "https://api.binance.com",
headers: {
"X-MBX-APIKEY":
"H48w9CLuTtTi955qWjcjjEKhh0Ogb3jnnluYucXXXXXXXXXXXXXXXX",
},
}).then((response) => {
var key = response.data.listenKey;
console.log(key, "created");
return key;
});
};
listenKey = createListenKey();
listenKey.then((key) => {
console.log(key);
});
最后一行的 console.log 打印未定义。这是为什么?
提前致谢!
你没有return异步函数的任何东西createListenKey
const asynF = async ()=>{
Promise.resolve(1).then(res=>{
//Simulating response from axios call
console.log(res)
})
// you are not returning anyting from this function equivalent of => return ;
}
asynF().then(res=>{
//this would log undefined
console.log(res)
})
如您所知,异步函数 return 承诺您有两个选项,使外部包装器也成为异步函数,并像下面那样使用 await
const key = await createListenKey(config)
否则
你可以简单地这样做
return createListenKey(config).then(res=>{
listenKey = res
})
不了解上下文就不能多说了。
我建议不要把 then 和 async wait 混在一起
因为 createListenKey()
函数没有 return 任何东西。该函数内 then 子句中的 return 语句在 then 块中限定范围。要 return 来自异步函数的值,您需要执行以下操作。
const createListenKey = async () => {
const response = await axios({
url: "/api/v3/userDataStream",
method: "POST",
baseURL: "https://api.binance.com",
headers: {
"X-MBX-APIKEY":
"H48w9CLuTtTi955qWjcjjEKhh0Ogb3jnnluYucXXXXXXXXXXXXXXXX",
},
})
var key = response.data.listenKey;
console.log(key, "created");
return key;
};
我想弄清楚这个问题已经有一段时间了,但它太令人困惑了,所以我想问一下。
var listenKey = "";
const createListenKey = async () => {
await axios({
url: "/api/v3/userDataStream",
method: "POST",
baseURL: "https://api.binance.com",
headers: {
"X-MBX-APIKEY":
"H48w9CLuTtTi955qWjcjjEKhh0Ogb3jnnluYucXXXXXXXXXXXXXXXX",
},
}).then((response) => {
var key = response.data.listenKey;
console.log(key, "created");
return key;
});
};
listenKey = createListenKey();
listenKey.then((key) => {
console.log(key);
});
最后一行的 console.log 打印未定义。这是为什么?
提前致谢!
你没有return异步函数的任何东西createListenKey
const asynF = async ()=>{
Promise.resolve(1).then(res=>{
//Simulating response from axios call
console.log(res)
})
// you are not returning anyting from this function equivalent of => return ;
}
asynF().then(res=>{
//this would log undefined
console.log(res)
})
如您所知,异步函数 return 承诺您有两个选项,使外部包装器也成为异步函数,并像下面那样使用 await
const key = await createListenKey(config)
否则
你可以简单地这样做
return createListenKey(config).then(res=>{
listenKey = res
})
不了解上下文就不能多说了。 我建议不要把 then 和 async wait 混在一起
因为 createListenKey()
函数没有 return 任何东西。该函数内 then 子句中的 return 语句在 then 块中限定范围。要 return 来自异步函数的值,您需要执行以下操作。
const createListenKey = async () => {
const response = await axios({
url: "/api/v3/userDataStream",
method: "POST",
baseURL: "https://api.binance.com",
headers: {
"X-MBX-APIKEY":
"H48w9CLuTtTi955qWjcjjEKhh0Ogb3jnnluYucXXXXXXXXXXXXXXXX",
},
})
var key = response.data.listenKey;
console.log(key, "created");
return key;
};