简体   繁体   English

java 脚本承诺行话

[英]java script promises lingo

I'm new to promises, so apologize for the newbie question.我是新的承诺,所以为新手问题道歉。 Inside my function, I have the following lines (middle of the function):在我的 function 中,我有以下几行(函数的中间):

...
const retPromise = await buildImgs(file, imgArray);
retPromise.then(async function () {
       console.log("completed build imgs");
       ...

My assumption was that the "then" from the promise would not execute until the await was completed.我的假设是 promise 中的“then”在等待完成之前不会执行。 but alas, it is acting like sync code, and the retPromise evaluating the "then" before the buildImgs is completed (as measured by my console.log flows).但是,唉,它就像同步代码一样,并且 retPromise 在 buildImgs 完成之前评估“then”(由我的 console.log 流测量)。 The result is an undefined retPromise.结果是一个未定义的 retPromise。

please help...what am I missing in the concept?请帮助...我在这个概念中遗漏了什么?

OK: after feedback, let me explaing further my question: I am trying to understand this async/sync flow and control concept:好的:反馈后,让我进一步解释我的问题:我正在尝试理解这个异步/同步流和控制概念:

const retVal = somefunc();
console.log(retVal);

const retVal = await somefunc();
console.log(retVal);

in the first case, if I understand sync / async code correctly, then I should have a possibility that retVal is undefined when the console.log finds it...在第一种情况下,如果我正确理解了同步/异步代码,那么当 console.log 找到它时,我应该有可能未定义 retVal ......

in the second case, I thought it would stop flow until that point that somefunc() completes, then the flow would continue.在第二种情况下,我认为它会停止流动,直到 somefunc() 完成,然后流动将继续。 However my reading seems to indicate it will still try to run the console.log message as a parallel thread.但是,我的阅读似乎表明它仍会尝试将 console.log 消息作为并行线程运行。 So this leads me to believe I would need to put the console.log inside of the.then after somefunc.所以这让我相信我需要将 console.log 放在 the.then 的 somefunc 之后。 Which leads me to promises.这让我做出了承诺。 So I made a promise return, which I see happening.所以我做了一个 promise 返回,我看到这正在发生。

However, the.then, as in my original post code, seems to post the console message "completed build imgs", before code inside my buildImgs completes (measured by time I know the function to take, and also console messages inside the buildImgs to help me with sequencing)但是,the.then,就像我原来的帖子代码一样,似乎在我的 buildImgs 中的代码完成之前发布了控制台消息“完成构建 imgs”(通过我知道要使用的 function 以及 buildImgs 中的控制台消息来衡量的时间来衡量)帮我测序)

so it seems to me I am still missing a fundamental on how to block flow for async code.所以在我看来,我仍然缺少有关如何阻止异步代码流的基础知识。 :( :(

When you use await construction the script waits until the promise resolves and return to your retPromise value from this promise.当您使用await构造时,脚本将等待 promise 解析并从此 promise 返回您的retPromise值。 So in this case better to choose one.所以在这种情况下最好选择一个。 Remove await and keep then , or keep await and use retPromise value.删除await并保留then ,或保留await并使用retPromise值。

Assuming that buildImgs is actually returning a promise (example)假设buildImgs实际上返回 promise (示例)

const buildImgs = (file, imgArray) => {
  return new Promise((resolve, reject) => {
    try {
      // ...
      resolve()
    } catch (err) {
      reject(err)
    }
  })
}

When you call await on a promise its already waiting for the promise to complete, if you remove the await on the call then you can use .then当您在 promise 上调用await时,它已经在等待 promise 完成,如果您在调用中删除await那么您可以使用.then

there are two ways to write promise handlers, the older way looks like this有两种方法可以编写 promise 处理程序,旧的方法看起来像这样

buildImgs(file, imgArray)
  .then(() => {
    console.log('im done')
  })
  .catch(err => {
    console.error(err)
  })

and the newer syntax和较新的语法

// you must declare "async" in order to use "await"
const asyncFunction = async () => {
  try {
    await buildImgs(file, imgArray)
    console.log('im done')
  } catch(err) {
    console.error(err)
  }
}
asyncFunction()

if you need the return value from the promise, then you would assign it to a variable如果您需要 promise 的返回值,则将其分配给变量

const ineedResponse = await buildImgs(file, imgArray)
console.log(ineedResponse)

// or

buildImgs(file, imgArray)
  .then(ineedResponse => {
    console.log(ineedResponse)
  })
  .catch(err => {
    console.error(err)
  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM