2017-10-19 12 views
0
私は何が起こっているかを理解するために歩行者用バージョンを構築することにより、約束について傾いてい

は、それは私は1つのexecutor機能がresolverejectを持ってconstructorに渡されたかどうかを確認しなければならない時点で立ち往生しています言えば十分引数として。JavaScriptの関数に渡される関数の引数の名前を取得するにはどうすればよいですか?

これはテストの結果です。

it('gets called with two different functions (funception!), resolve and reject', function() { 
     var promise = new $Promise(executor); // eslint-disable-line no-unused-vars 
     var argsPassedIntoExecutor = executor.calls.argsFor(0); 

     expect(argsPassedIntoExecutor.length).toBe(2); 
     var resolve = argsPassedIntoExecutor[0]; 
     var reject = argsPassedIntoExecutor[1]; 

     expect(typeof resolve).toBe('function'); 
     expect(typeof reject).toBe('function'); 
     expect(resolve).not.toBe(reject); 
    }); 

私がこれまで持っているもの:

function $Promise(fnc) { 
    if (typeof arguments[0] !== 'function') { 
    throw new TypeError('Sorry argument passed to $Promise should an executor function'); 
    } 

    function ArgumentsToArray(args) { 
    return [].slice.apply(args); 
    } 

    console.log(ArgumentsToArray.apply(fnc)); 

    this._state = 'pending'; 
    this._value = null; 
    this._internalResolve = function(data) { 
    if (this._state !== 'pending') return; 
    this._value = data; 
    this._state = 'fulfilled'; 
    }; 
    this._internalReject = function(data) { 
    if (this._state !== 'pending') return; 
    this._value = data; 
    this._state = 'rejected'; 
    }; 

    return fnc(); 
} 

これは私が(上記からの抜粋)しようとしたものですが、無駄に:

function ArgumentsToArray(args) { 
    return [].slice.apply(args); 
    } 

    console.log(ArgumentsToArray.apply(fnc)); 

任意の助けが理解されるであろう!

+0

WTHは 'ArgumentsToArray'が行うはずですか?どこでも配列を扱う必要はありませんか? 'fnc()'を呼び出すときには、リゾルバ関数を引数として渡すだけです。 – Bergi

答えて

1

あなたの質問には、名前付き引数はJavaScriptには存在しません。私たちはlengthプロパティと引数の非構造化を持つ関数arity(警告あり)を持っています。したがって、「引数の名前」をテストする方法はありません。あなたのテストのために:

const spy = (resolve, reject) => { 
    expect(typeof resolve).toBe("function"); 
    expect(typeof resolve).toBe("function"); 

}; 

あなたのコンストラクタにこのスパイを渡してください。

これは興味深い試みですが、スペックから試してみてください。この仕様で導入されたPromiseのコンストラクタは、多くの場合、発見可能性のために(constructorプロパティで)検出されます。

https://promisesaplus.com/は、resolveという簡単な手順を最初に理解して再実装しようとしていますが、仕様には(npmパッケージとして配布される)テストスイートがあります。

関連する問題