<!DOCTYPE html> <htmllang="en"> <head> <metacharset="UTF-8"> <metaname="viewport"content="width=device-width, initial-scale=1.0"> <title>Promise basic syntax</title> </head> <body> <script> /** * create a Promise instance p by use new Promise(function(resolve, reject) {}); * new Promise() receive a function as parameter, * the first parameter of the function is usually named resolve, * the second parameter of the function is usually named reject. * We can use function resolve() and reject() to setup the status of instance p, * When the function execute successfully, use the resolve() to update status to success. * When the function execute failed, use the reject() to update status to fail. */ const p = newPromise(function(resolve, reject) { setTimeout(function() { // resolve // let data = 'user data in database'; // resolve(data); // reject let err = 'read the data failed'; reject(err); }, 1000); }); /** * then() has two parameters that are two functions. * The first function will execute when the resolve() function executed, * The second function will exxcute when the reject() function executed, * parameters can be transferred */ p.then(function(value) { console.log(value); // user data in database }, function(reason) { console.log(reason); // read the data failed }); </script> </body> </html>