首页 > 解决方案 > 我的异步函数中的等待变量似乎没有逐行执行

问题描述

我有两个等待函数的变量。我只是想在它们完成后对它们进行控制台记录,但是当它跳过时我对它们都没有定义。

在等待功能首先发生之后发生的控制台日志。然后函数在几秒钟后完成。

async onSubmit(event) {
   event.preventDefault();

   const coverImage = await ipfs.files.add(this.state.buffer, (error, result) =>{
   if(error){
    console.error(error)
    return
   }

  console.log('Here is: ', result[0].hash)
  //Return the hash value
  return result[0].hash
  })

  const contents = await ipfs.files.add(this.state.contentBuffer, (error, result) =>{
  if(error){
    console.error(error)
    return
  }

  console.log('Here is: ', result[0].hash)
  //Return the hash value
  return result[0].hash
  })

  let answer ={thePic: coverImage, theContents: contents}

  console.log(answer)   //This shows as {thePic: undefined, theContents: 
  //undefined}

}

我希望控制台日志在完成之后coverImagetheContents但它会立即发生。

标签: async-awaitjsx

解决方案


https://github.com/ipfs/interface-ipfs-core/blob/master/SPEC/FILES.md#add

“如果没有通过回调,则返回一个承诺。”

await仅当您调用返回承诺的函数时才有意义。如果您在 async 调用之后修改代码以在 async 函数中继续,则返回的值应该是您正在寻找的结果,并按照您期望的顺序发生。

const imageResult = await ipfs.files.add(this.state.buffer);
const coverImage = imageResult[0].hash;

如果您想处理错误情况,请将整个等待调用的集合包装在 try/catch 中;错误将是任何中间承诺的错误条件引发的错误。


推荐阅读