【发布时间】:2019-02-07 03:14:53
【问题描述】:
我想创建一个withPromise,其工作方式如下:
import {useState, withEffect} from "react";
function usePromise(promise, default=null) {
// This state variable will hold the value of our promise.
// We allow the user to pass in a default value that'l be returned
// as long as the promise hasn't been resolved.
let value, setValue = useState(default);
// Ensure that this is only re-run when the promise changes.
withEffect(() => {
promise.then(setValue)
}, [promise])
return value;
}
如果promise 参数从不改变,这很有效,但我希望它能够适应传入新的promise,因为此时可能会导致竞争条件。
-
promise1传递给usePromise -
promise2传递给usePromis-e -
promise2已解析,将值设置为value2 -
promise1已解析,将值设置为value1
在这一系列事件中,新 Promise 的值被旧 Promise 的值覆盖,后者稍后解决。
但是由于承诺是不可取消的,我看不到有一种方法可以在承诺的回调中检查新的承诺在等待解决时是否已传入。
有什么办法可以做到吗?
【问题讨论】:
标签: javascript reactjs promise react-hooks