首页 > 其他分享 >js 异步改成同步Promise

js 异步改成同步Promise

时间:2023-08-23 09:47:54浏览次数:38  
标签:function 异步 resolve value js Promise reject promise

function Promise(executor) {
    let self = this;
    if (typeof executor !== 'function') throw new TypeError('Promise resolver ' + executor + ' is not a function');
    if (!(self instanceof Promise)) throw new TypeError('undefined is not a promise');

    self.state = 'pending';
    self.value = undefined;
    self.onfulfilledCallbacks = [];
    self.onRejectedCallbacks = [];

    const change = function change(state, value) {
        if (self.state !== 'pending') return;
        self.state = state;
        self.value = value;

        const callbacks = self.state === "fulfilled" ? self.onfulfilledCallbacks : self.onRejectedCallbacks;
        for (let i = 0; i < callbacks.length; i++) {
            let callback = callbacks[i];
            if (typeof callback === 'function') callback(self.value);
        }

    };

    try {
        executor(function resolve(value) {
            change('fulfilled', value);
        }, function reject(reason) {
            change('rejected', reason);
        });
    } catch (err) {
        change('rejected', err.message);
    }
}

const resolvePromise = function resolvePromise(promise, x, resolve, reject) {
    if (x === promise) throw new TypeError('Chaining cycle detected for promise #<Promise>');
    if (x !== null && /^(object|function)$/i.test(typeof x)) {
        let then;
        try {
            then = x.then;
        } catch (err) {
            reject(err);
        }
        if (typeof then === 'function') {
            let called = false;
            try {
                then.call(x, function onfulfilled(x) {
                    if (called) return;
                    called = true;
                    resolvePromise(promise, x, resolve, reject);
                }, function onRejected(r) {
                    if (called) return;
                    called = true;
                    reject(r);
                });
            } catch (err) {
                if (called) return;
                reject(err);
            }
            return;
        }
    }
    resolve(x);
};
const handle = function handle(callback, value, promise, resolve, reject) {
    try {
        let x = callback(value);
        resolvePromise(promise, x, resolve, reject);
    } catch (err) {
        reject(err);
    }
};
Promise.prototype = {
    constructor: Promise,
    then: function then(onfulfilled, onRejected) {
        const self = this;
        let promise = null;
        if (typeof onfulfilled !== 'function') {
            onfulfilled = function onfulfilled(value) {
                return value;
            };
        }
        if (typeof onRejected !== 'function') {
            onRejected = function onRejected(reason) {
                throw reason;
            };
        }
        promise = new Promise(function (resolve, reject) {
            switch (self.state) {
                case 'fulfilled':

                    handle(onfulfilled, self.value, promise, resolve, reject);

                    break;
                case 'rejected':

                    handle(onRejected, self.value, promise, resolve, reject);

                    break;
                default:
                    self.onfulfilledCallbacks.push(function (value) {
                        handle(onfulfilled, value, promise, resolve, reject);
                    });
                    self.onRejectedCallbacks.push(function (reason) {
                        handle(onRejected, reason, promise, resolve, reject);
                    });
            }
        });
        return promise;
    },
    catch: function my_catch(onRejected) {
        return this.then(null, onRejected);
    }
};
if (typeof Symbol !== "undefined") Promise.prototype[Symbol.toStringTag] = 'Promise';
Promise.resolve = function resolve(value) {
    return new Promise(function (resolve) {
        resolve(value);
    });
};
Promise.reject = function reject(reason) {
    return new Promise(function (_, reject) {
        reject(reason);
    });
};
const isPromise = function isPromise(x) {
    if (x !== null && /^(object|function)$/i.test(typeof x)) {
        if (typeof x.then === 'function') {
            return true;
        }
    }
    return false;
};
Promise.all = function all(promises) {
    if (!Array.isArray(promises)) throw new TypeError('promises must be an Array');
    let n = 0,
        results = [];
    return new Promise(function (resolve, reject) {
        for (let i = 0; i < promises.length; i++) {
            (function (i) {
                let promise = promises[i];
                if (!isPromise(promise)) promise = Promise.resolve(promise);
                promise.then(function onfulfilled(value) {
                    n++;
                    results[i] = value;
                    if (n >= promises.length) resolve(results);
                }).catch(function onRejected(reason) {
                    reject(reason);
                });
            })(i);
        }
    });
};
Promise.deferred = function deferred() {
    const result = {};
    result.promise = new Promise(function (resolve, reject) {
        result.resolve = resolve;
        result.reject = reject;
    });
    return result;
};

const _promise_ = new Promise((resolve, reject) => {
    console.log(`sync..`)
    resolve(101)
})

_promise_.then((data) => {
    console.log(`sync..`);
    console.log(data);
})

_promise_.then((data) => {
    console.log(888);
    console.log(data);
})

let p1 = new Promise(function (resolve, reject) {
    resolve(`宝哥说给你10000000`);
});
p1.then(e => console.log(e));

let p2 = new Promise(function (resolve, reject) {
    reject(`阿布反手拒绝你一个99999`);
});
p2.catch(err => console.log(`err`, err));

Promise.resolve("13122223333").then(v => console.log(v));

  

标签:function,异步,resolve,value,js,Promise,reject,promise
From: https://www.cnblogs.com/yoyo1216/p/17650268.html

相关文章

  • JS中的JSON.Stringify 方法详解
    JSON.stringify是JavaScript中的一个方法,用于将JavaScript对象转换为JSON字符串。语法:JSON.stringify(value,replacer,space)参数说明:value:要转换为JSON字符串的值。replacer(可选):用于过滤和转换结果的函数或数组。如果是函数,则只转换函数返回的结果;如果是数组,则......
  • webman:配置异常处理返回json格式(v1.5.7)
    一,添加一个除0错的异常代码:页面显示效果如图:二,配置:php代码1,config/123456789101112131415161718<?php/** *Thisfileispartofwebman. * *LicensedunderTheMITLicense *Forfullcopyrightandlicenseinformation......
  • JSON文件如何添加注释?
    JSON(JavaScriptObjectNotation)的设计是简洁和明确的,它不支持注释。这是JSON设计的决策之一,目的是使JSON保持尽可能简单和纯粹。但在实践中,很多时候,开发者确实会想在JSON文件中添加注释,以帮助解释或标记某些部分。虽然JSON标准不支持注释,但你仍然可以采取以下策略:使用替代文件:使用......
  • Json 格式处理
    Jackson1.maven依赖导入<!--https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind--><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId>......
  • 原生JS 根据需求生成表格
    <!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>Document</title><style>td{padding:10px;border-collapse:collapse;}</styl......
  • JS传递参数
    JS传递参数ECMAScript中在向参数传递基本类型的值时,被传递的值会被赋值给一个局部变量(即命名参数,或者用ECMAScript的概念来说,就是arguments对象中的一个元素)。在向参数传递引用类型值时,会把这个值在内存中的地址赋值给一个arguments的一个(局部)变量,因此这个局部变量的变化会......
  • flask接收json,开启服务demo
    demofromflaskimportFlask,render_template,request,jsonifyapp=Flask(__name__)@app.route('/',methods=['GET','POST'])defindex():processed_data=Noneifrequest.method=='POST':try......
  • 安卓中如何使用AsyncTask完成异步定时任务?
    在Android中,可以使用AsyncTask类来实现异步定时任务。下面是一个简单的例子,演示如何使用AsyncTask实现异步定时任务:javaCopycodeimportandroid.os.AsyncTask;importandroid.os.Bundle;importandroid.support.v7.app.AppCompatActivity;importandroid.widget.TextVi......
  • 使用EasyPlayer.js,通过设置解码器参数实现H.265音频解码
    EasyPlayer是一款稳定且流畅的流媒体播放器,它能够支持H.264和H.265视频播放。该播放器能够处理各种视频流格式,包括RTSP、RTMP、HLS、FLV和WebRTC等。EasyPlayer具备多个版本,例如EasyPlayer-RTSP、EasyPlayer.js和EasyPlayerPro,以满足不同用户在不同场景下的需求。此外,EasyPlayer还......
  • nodejs 使用exec ,execFile,spawn运行子进程区别,以及如何正确的的关闭子进程
    exec,execFile,spawn都是运行一个子进程,但是在不同的操作系统上用法和表现有很大差异。linux/unixexec运行子进程需要创建一个终端环境(命令行窗口),然后在其中运行命令,execFile则不需要,因此在linux/unix上,execFile的效率更高。windows在windows平台上,运行脚本程序(如批处理.bat)必须有......