const ret = () => new Promise(resolve => setTimeout( () => resolve('somestring'), 1000));
async function wrapper() {
let someString = await ret();
return someString;
}
console.log( wrapper() );
Run Code Online (Sandbox Code Playgroud)
它记录Promise { <pending> }; 为什么它会返回Promise而不是'somestring'?
我正在使用Babel ES7预设来编译它.
我在 React 中有一个 dataService 函数来执行我的 API 获取。我尝试转换为 async/await 块,但似乎遇到了障碍。
使用承诺:
const dataService = (url, options, dataToPost) => {
return (dispatch, getState) => {
const { requestAction, successAction, failureAction } = options.actions;
if (options.shouldRequest(getState())) {
dispatch(requestAction());
const promise = axios.get(url, { withCredentials: true });
return promise
.then(response => {
if (response.status === 200) {
return dispatch(successAction(response, dispatch));
}
return Promise.reject(response);
})
.catch(error => {
if (error.response.status === 302) {
window.location = '/view';
}
dispatch(openErrorDialog());
return dispatch(failureAction(error));
});
}
return Promise.reject(new Error('FETCHING')); …Run Code Online (Sandbox Code Playgroud) 我的情况:
let waiting = function () {
return new Promise(resolve => {
console.log('awaiting...');
setTimeout(function () {
resolve();
}, 1000)
});
};
let waitingAsync = async function () {
console.log('start...');
await waiting();
console.log('stop...');
};
waitingAsync();
console.log('done...');Run Code Online (Sandbox Code Playgroud)
代码中有两件事我不明白:
首先:
await waiting();
Run Code Online (Sandbox Code Playgroud)
waiting是一个同步函数(因为它没有async关键字)。那么,为什么我可以等待一个同步函数呢?
第二:
为什么done...完成waitingAsync功能后不能等待消息?
主要问题:waitingAsync是一个异步函数,为什么await调用它时不需要关键字?只是waitingAsync()代替await waitingAsync().
如果我可以 await waitingAsync(),done...消息将最后打印。
我正在尝试访问df-chips.
然而,乍一看并没有加载,所以我尝试使用asyng / await. 但是......我不擅长javascript,所以我做错了一些事情,而且我不知道是什么。
这是我的代码:
// Function to catch asynchronous that node
const asyncQuerySelector = async (node, query) => {
try {
if (node.querySelector(query)){
return await node.querySelector(query);
}
} catch (error) {
console.error(`Cannot find ${query ? `${query} in`: ''} ${node}.`, error);
return null;
}
};
const root = document.querySelector('#messageList')
const foo = asyncQuerySelector(root, 'df-chips')
Run Code Online (Sandbox Code Playgroud)
但我得到了一个null承诺的结果: