【问题标题】:How do i write promises in javascript我如何在javascript中编写承诺
【发布时间】:2021-04-06 08:53:21
【问题描述】:

我试图写一个承诺,但似乎遗漏了一些东西。这是我的代码:

const myPromise = new Promise(() => {
      setTimeout(() => {
        console.log("getting here");
        return setinputs({ ...inputs, images: imageAsUrl });
      }, 100);
    });
    myPromise
      .then(() => {
        console.log("getting here too");
        firebase.database().ref(`collection/${idNode}`).set(inputs);
      })
      .then(() => {
        console.log("all is set");
      })
      .catch((err) => {
        console.log(err);
      });

如果我运行程序,承诺的第一部分正在执行,但所有.then() 函数都没有执行。我该如何解决这个问题?

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

在这个方案中,promise 回调有一个 (resolve) 或两个 (resolve,reject) 参数。

let p = new Promise((resolve, reject)=> {
   //do something 
   //resolve the promise:
   if (result === "ok") {
      resolve(3);
   }
   else {
      reject("Something is wrong");
   }
});

p.then(res => {
   console.log(res); // "3"
}).catch(err => {
    console.error(err); //"Something is wrrong
 });

当然,现在你可以在很多情况下使用 async + await。

【讨论】:

  • 但即使使用 async await 有时你也必须编写自己的承诺,对吧?
  • 是的,就像您使用计时器一样。您也可以为此使用可观察的 rxjs。现在大部分时间都在等待(一些异步调用)。
  • 不是我的情况...?
【解决方案2】:

您需要使用resolve() 解决承诺,并从firebase 返回承诺,以便链中的下一个.then 正常工作。

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    console.log("getting here");
    // You have to call resolve for all `.then` methods to be triggered
    resolve({ ...inputs, images: imageAsUrl });
  }, 100);
});
myPromise
  .then((inputs) => {
    console.log("getting here too");
    // You have to return a promise in a .then function for the next .then to work properly
    return firebase.database().ref(`collection/${idNode}`).set(inputs);
  })
  .then(() => {
    console.log("all is set");
  })
  .catch((err) => {
    console.log(err);
  });

【讨论】:

    猜你喜欢
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多