asyncとawait

18687 ワード

asyncとawaitは実は戦術皮で、彼女の本質はPromiseで、毎回関数がPromiseの対象に帰るのでさえすれば、あなたはawaitそれを使うことができて、同期のプログラムの方式のように獲得することができます.
console.log("before");
const user = getUser(1);
console.log("Go: user", user);
console.log("after");

//callback
//promise
//asyn/await
function getUser(id) {
  setTimeout(() => {
    console.log("Get user from database");
    return { id: id, username: "helloworld" };
  }, 2000);
}
//   :
// before
// Go: user undefined
// after
// Get user from database
console.log("before");
const user = getUser(1, user => {
  getRepositories(user, repos => {
    repos.map(repo => {
      console.log(repo);
    });
  });
});
console.log("after");

//callback

//promise
//asyn/await
function getUser(id, callback) {
  setTimeout(() => {
    console.log("Get user from database");
    callback({ id: id, username: "helloworld" });
  }, 2000);
}

function getRepositories(username, callback) {
  setTimeout(() => {
    console.log("get Repositories from database");
    callback([1, 2, 3]);
  }, 1000);
}
//   
// before
// after
// Get user from database
// get Repositories from database
// 1
// 2
// 3
console.log("before");
getUser(1).then(res => {
  console.log(res);  

//promise 
//asyn/await
function getUser(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("Get user from database");
      resolve({ id: id, username: "helloworld" });
    }, 2000);
  });
}

function getRepositories(username, callback) {
  setTimeout(() => {
    console.log("get Repositories from database");
    callback([1, 2, 3]);
  }, 1000);
}

console.log("before");
getInfo();
console.log("after");
//asyn/await
async function getInfo() {
  const user = await getUser(1);
  console.log("Go: getInfo -> user", user);
  const abc = await getRepositories(1);
  console.log("Go: getInfo -> abc", abc);
}

function getUser(id) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({ id: id, username: "helloworld" });
    }, 2000);
  });
}

function getRepositories(username) {
  return new Promise((resolve, rerject) => {
    setTimeout(() => {
      console.log("get Repositories from database");
      resolve([1, 2, 3]);
    }, 1000);
  });
}