简体   繁体   English

Javascript,promise.then()函数首先执行

[英]Javascript, promise.then() function executed first

I apologize in advance for overlooking something fundamental but I can't get my head around the following issue. 我为忽略一些基本内容表示歉意,但我无法解决以下问题。

I want to create a user on the server, subsequently showing all users (including the new one). 我想在服务器上创建一个用户,随后显示所有用户(包括新用户)。 To simplify things I have put an alert in the "then" clause. 为简化起见,我在“ then”子句中添加了警报。 The problem is that the alert comes up before the "CreateUser" on the server has completed. 问题是在服务器上的“ CreateUser”完成之前出现警报。 According to the doc, "then" is executed when the promise has completed. 根据文档,“那么”将在诺言完成后执行。 Why is it the inverse on my pc ? 为什么在我的电脑上是相反的?

function createUser(newUser) {   
    userService.create(newUser) // Post creating new user
        .then(      
        alert('Why do I come up before completion of the  userService.create() function  ?')
        );  
}

This is the userService.create() function: 这是userService.create()函数:

function create(user) {
//    alert(user);
    const requestOptions = {
        method: 'POST',
        headers: { ...authHeader(), 'Content-Type': 'application/json' },
        body: user
    };

    return fetch('/Client/Create', requestOptions).then(handleResponse, handleError);
}

handleResponse: handleResponse:

function handleResponse(response) {
    return new Promise((resolve, reject) => {

....

handleError: handleError:

function handleError(error) {
    return Promise.reject(error && error.message);
}

Thanks a million. 太感谢了。

change 更改

function createUser(newUser) {   
    userService.create(newUser) // Post creating new user
        .then(      
        alert('Why do I come up before completion of the  userService.create() function  ?')
        );  
}

to: 至:

function createUser(newUser) {   
    userService.create(newUser) // Post creating new user
        .then(function(){
          alert('Why do I come up before completion of the  userService.create() function  ?');
        });  
}

then 然后

then requires a function to be passed, so do this: then需要传递一个函数,因此请执行以下操作:

userService.create(newUser).then(() => {
    alert('Why do I come up before completion of the  userService.create() function  ?')
});

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

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