将异步函数的值设置为 .then 的返回值



edit:也许我把我的例子简化得太多了。让我再试一次

file1.js
import conditonFunction from './conditonFunction'
console.log(conditonFunction()) 

file2.js
import asyncFunction from './asyncFunction'

export const conditonFunction = () => {
if (condition) {
return 'this doesnt matter'
} else {
asyncFunction().then(res => {
return res[0].whatever
})
}
}

如果不满足我的条件,我希望记录的值conditonFunctionasyncFunction内部的res

我错过了什么?

另一种方法是使用async函数。

function asyncFunction() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(7);
}, 2000);
});
}
async function main() {
var res = await asyncFunction(); 
console.log(res);
}
main();
Wait for 2 seconds...

你似乎在寻找

asyncFunction().then(res => {
return res[0].whatever;
}).then(console.log);

或者干脆

asyncFunction().then(res => {
console.log(res[0].whatever);
});

最新更新