如何使脚本在等待承诺结果之前继续进行?

时间:2020-01-29 06:36:23

标签: javascript

我一直在努力寻找解决方案。

我保证等待从外部服务器获取用户信息,然后确定要重定向到下一页的页面。但是,我的脚本不是在等待诺言返回,而是继续执行下一行代码,这些代码将重定向到错误的页面,然后,一旦诺言返回,它将再次重定向到正确的页面。

我想要的是等待诺言并基于返回的数据的代码,然后重定向到正确的页面。

function redirect(user){

   return new Promise((resolve, reject) => {
     //send request to external server and waiting for the response
     //if response == 1 then redirect to page1

  }
}

redirect(user).then(() => {
   //redirect to page 2 here
});

但是,结果始终是重定向到page2,然后重定向到page1

2 个答案:

答案 0 :(得分:1)

以下是有关诺言用法的示例

function redirect(user) {
  return new Promise((resolve, reject) => {
    fetch(user)
      .then(response => response.json())
      .then(data => resolve(data.data))
      .catch((error) => {
        reject(error);
      })
  })
}

redirect("https://reqres.in/api/users/2").then((data) => {
  // You should make redirection here
  /*
  if(data == 1) {
    // your operation
  } else {
    // another operation
  }
  */
  console.log(data)
});

答案 1 :(得分:1)

您的redirect还必须等待请求完成。如果没有详细的实现,我想您没有用于服务器请求的await

我在这里猜测您的一些实现。

https://jsfiddle.net/4g6juyf5/1/

function redirect(user) {
  return new Promise(async (resolve, reject) => {
    // Wait for the first page to finish
    const result = await fetch('https://jsonplaceholder.typicode.com/todos/1');

    // finished then resolve
    if (result != undefined) {
      console.log("Page 1 requested")
      resolve(true)
    }
  })
}

const user = "John";

redirect(user).then(async () => {
  //redirect to page 2 here
  console.log("Requesting Page 2")
  const result = await fetch('https://jsonplaceholder.typicode.com/users')
});

注意,此代码仍然很草率。如果您发布实施,我们也许可以对其进行改进。