简体   繁体   English

使用 then/catch 承诺结果

[英]Promise result with then/catch

I test ES6 Promise in react APP, but i've not result on my .then :我在 react APP 中测试了 ES6 Promise,但我的 .then 没有结果:

function addItem (value) {
  return new Promise((resolve, reject) => {
    document.getElementById('todo').innerHTML += `<li>${value}</li>`;
  });
}

addItem(value).then(() => {
  alert('then !');
}).catch((err) => {
  console.log(err)
})

My function is executed, but i've not event on my then.我的功能已执行,但我当时没有事件。

Do you know where i was wrong ?你知道我错在哪里吗? Thank you !谢谢 ! :) :)

Promises are used for asynchronous tasks. Promise 用于异步任务。 There's no point in using them to execute synchronous code.使用它们来执行同步代码毫无意义。 In you example, then() is not working because you never resolve the promise.在您的示例中, then()不起作用,因为您从未解决过承诺。 In order to resolve it, you need to call resolve() .为了解决它,您需要调用resolve()

You need to call either reject or resolve in your promise.您需要在您的承诺中调用拒绝或解决。

function addItem (value) {
  return new Promise((resolve, reject) => {
    document.getElementById('todo').innerHTML += `<li>${value}</li>`;
    resolve();
  });
}

You need to resolve your promise, for example:您需要解决您的承诺,例如:

function addItem (value) {
  return new Promise((resolve, reject) => {
    document.getElementById('todo').innerHTML += `<li>${value}</li>`;
    resolve(10);
  });
}

addItem(value).then((data) => {
  alert('then !');
  console.log(data);// 10
}).catch((err) => {
  console.log(err)
})

You forgot to call the resolve and reject function in your Promise.你忘记在你的 Promise 中调用resolvereject函数。

resolve is a function that you call when you're done with your action. resolve是您完成操作后调用的函数。

resolve();

The argument that you pass to resolve() is what you get back in the then function.您传递给resolve()的参数是您在then函数中返回的参数。

reject is a function that you call when there's a error with your action. reject是当您的操作出现错误时调用的函数。 If you don't have anything to reject then you can just leave it out and you won't have to call it.如果你没有什么要拒绝的,那么你可以把它放在外面,你就不用打电话了。

reject();

the argument that you pass to reject() is what you get back in the catch function.您传递给reject()的参数是您在catch函数中返回的参数。

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

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