promise 让我困惑。
我正在尝试制作一个模拟数据服务来模仿 axios。
我的模拟 put
调用将 targetUrl 传递给 _fetch
,然后它会查看它是否是有效的 url,并返回一个带有延迟的 .resolve 的新 Promise
const _returnResponse = (mockData, time = 0) => new Promise((resolve) => {
setTimeout(() => {
resolve(mockData);
}, time);
});
或者一个带有延迟的 .reject 的新 Promise
const _returnError = (time = simulatedDelay) => {
const returnValue = new Promise(((resolve, reject) => {
setTimeout(() => {
reject(new Error('error'));
}, time);
}));
return returnValue;
};
但是当我进行模拟 put
调用时,它会返回一个模拟数据,调用方法将其解释为成功,并且控制台会在其 .then 中记录
put(target, putBody) {
const returnValue = _fetch(target, simulatedDelay)
returnValue.then(response => _console('PUT', target, response, putBody));
return returnValue;
},
但是如果目标控制台无效,则会记录 Uncaught Error
或者这可以正确处理错误,但控制台会记录未定义的响应
put(target, putBody) {
const returnValue = _fetch(target, simulatedDelay).then(response => _console('PUT', target, response, putBody));
return returnValue;
},
调用方法如下:
saveStuff({ commit, state }, newStuff) {
//other code
return this.$mockAxios.put(url, putBody)
.then((response) => {
return response;
});
},
我觉得我完全错过了一些东西,我已经研究了几个小时,但我仍然没有明白。
最佳答案
作为问题的直接答案:是的,您可以在创建 Promise 后将 .then() 添加到 Promise 中。
示例:
const hi = new Promise((resolve, reject) => {
setTimeout(() => resolve('hello'), 2000);
});
hi.then(result => console.log(result));
至于让您感到困惑的 Promise,我建议(除了更多阅读之外)在 IDE 中使用 setTimeout 进行大量操作。我知道您已经在模拟中使用了 setTimeout,但进一步将其剥离并仅在其自己的文件中运行代码,以便您控制整个环境。使用大量的 console.log('blah') 来查看顺序等。还要确保您同样熟悉回调,因为 Promise 只是回调的语法糖。尝试同时阅读 JS 事件循环 - 如果您知道回调/ promise 如何以及何时执行,它可能会提供一些上下文。
请注意,您甚至可以在回调解决或拒绝后添加 .then()。因此,术语“ promise ” - 它实际上是您的 .then() 函数将运行的 promise 。 https://en.wikipedia.org/wiki/Promise_theory
const hi = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('one second');
resolve();
}, 1000);
});
setTimeout(() => {
hi.then(() => console.log('two seconds. this executes approximately a full second after the first promise has resolved'));
}, 2000);
关于javascript - 您可以在创建 Promise 后添加 .then 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56086294/