【问题标题】:Setting value of async function to the value of the return of the .then [duplicate]将异步函数的值设置为.then的返回值[重复]
【发布时间】:2018-10-24 19:17:05
【问题描述】:

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

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
    })
  }
}

如果我的条件不满足,我希望conditonFunction 的记录值是resasyncFunction 的值

我错过了什么?

【问题讨论】:

  • 你真的给asyncFunction()打了两次电话吗?还请修复语法错误 - then( 调用缺少右括号。

标签: javascript ecmascript-6 promise es6-promise


【解决方案1】:

另一种方法是使用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...

【讨论】:

    【解决方案2】:

    你似乎在寻找

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

    或者干脆

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-12
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 2014-01-17
      • 1970-01-01
      相关资源
      最近更新 更多